<?php
namespace api\components;

use Yii;
use yii\web\Response;

/**
 * Site controller
 */
class Controller extends \yii\web\Controller
{
    public $format     = 'json';
        
    public function init() {
        
        $this->format = Yii::$app->request->get('format', 'json');
        return parent::init();
    }

    public function beforeAction($action)
    {
        return parent::beforeAction($action);
    }

    /**
     *
     */
    public function afterAction($action, $result)
    {
        $result   = parent::afterAction($action, $result);
        if (!is_array($result)) {
            $result = ['code' => 0, 'message' => (string) $result];
        }
        elseif (!isset ($result['code']) || $result['code'] === true) {
            $result['code'] = 0;
        }
        
        if (!isset($result['message'])) {
            $result['message'] = Yii::t('error', $result['code']);
        }
        
        if ($this->format == 'jsonp')
        {
            $result = [
                'data'=> $result, 
                'callback' => Yii::$app->request->getQueryParam('callback', 'callback'),
                ];
        }
        
        switch ($this->format) {
            case 'xml':
                Yii::$app->response->format = Response::FORMAT_XML;
                break;
            case 'jsonp':
                Yii::$app->response->format = Response::FORMAT_JSONP;
                break;
            default :
                Yii::$app->response->format = Response::FORMAT_JSON;
        }
        Yii::$app->response->data = $result;
        Yii::$app->response->send();
        return $result;
    }

}
